import { Component, OnInit, Input } from '@angular/core';
import { ConfirmationService } from 'primeng/primeng';
import { DragerAssembly, Assembly, AssemblyStyles, AssemblyValidators, AssemblyConfigs } from '../fb-design.model';
import { FormDesignService } from '../fb-design.service';
import { MdlSnackbarService } from '@angular-mdl/core';
@Component({
    selector: 'fb-drawer',
    templateUrl: './fb-drawer.component.html',
    styleUrls: ['./fb-drawer.component.scss'],
    providers: [FormDesignService]
})
export class FormDrawerComponent implements OnInit {
    /**当前表单 */
    formIdValue: number;
    /**可用控件列表 */
    availableAssembly: DragerAssembly[];
    /**当前拖放控件 */
    draggedAssembly: DragerAssembly;
    /**已选择全部控件 */
    assemblies: Assembly[] = [];
    /**当前选择控件 */
    assembly: Assembly;

    @Input()
    set formId(formId: number) {
        if (!formId) return;
        this.formIdValue = formId;
        this.assemblies = [];
        this.loadFormAssemblies();
    }
    get formId(): number { return this.formIdValue; }

    @Input()
    names: string[];
    
    constructor(
        private formDesignService: FormDesignService,
        private mdlSnackbarService: MdlSnackbarService,
        private confirmationService: ConfirmationService) {
    }

    ngOnInit() {
        /** 加载可用组件列表 */
        this.formDesignService.getAvalibleAssemblies().subscribe(assemblies => {
            this.availableAssembly = assemblies;
        });
        /** 初始化值*/
        this.assembly = new Assembly({
            attributes: new AssemblyStyles(),
            validators: new AssemblyValidators(),
            configs: new AssemblyConfigs()
        });
    }

    /**保存面板 */
    save() {
        this.formDesignService.saveFromDrager(this.assemblies)
            .subscribe(data => { this.mdlSnackbarService.showToast("表单存盘成功！") })
    }

    /**删除组件 */
    remove() {
        this.formDesignService.removeAssemblyInst(this.assembly.id)
            .subscribe(data => {
                this.assemblies.forEach((assembly, index) => {
                    if (assembly.id == this.assembly.id) {
                        this.assemblies.splice(index, 1);
                        return;
                    }
                });
                this.assembly = new Assembly({
                    attributes: new AssemblyStyles(),
                    validators: new AssemblyValidators(),
                    configs: new AssemblyConfigs()
                });
            });
    }
    /**清空面板 */
    clear() {
        this.confirmationService.confirm({
            header: '确认',
            message: '您确定要清空全部组件吗？',
            accept: () => {
                this.formDesignService.clearFormDrager(this.formId)
                    .subscribe(data => {
                        this.assemblies = [];
                        this.assembly = new Assembly({
                            attributes: new AssemblyStyles(),
                            validators: new AssemblyValidators(),
                            configs: new AssemblyConfigs()
                        });
                    });
            }
        });
    }

    dragStart(event, assembly: DragerAssembly) {
        this.draggedAssembly = assembly;
    }

    drop(event) {
        if (this.draggedAssembly) {
            //生成基础属性
            let assemblyAttributes = this.draggedAssembly.dftAttr ? JSON.parse(this.draggedAssembly.dftAttr) : {};
            assemblyAttributes.x = parseInt(event.offsetX);
            assemblyAttributes.y = parseInt(event.offsetY);
            //生成实例对象
            this.assembly = new Assembly({
                value: this.draggedAssembly.dftValue || "",
                formId: this.formId,
                controlType: this.draggedAssembly.typeCode,
                authFlag: this.draggedAssembly.authFlag,
                attributes: new AssemblyStyles(assemblyAttributes),
                validators: new AssemblyValidators(),
                configs: new AssemblyConfigs()
            });
            this.assembly.attributes.refreshStyle();
            //保存到数据库
            this.formDesignService.formAddAssembly(this.assembly)
                .subscribe(data => {
                    this.assembly.id = data;
                    if (this.assemblies.length == 0) {
                        //fix BUG:拖拽第一个组件时不显示
                        this.loadFormAssemblies();
                    } else {
                        this.assemblies.push(this.assembly);
                        setTimeout(() => this.onAssemblyClick(this.assemblies[this.assemblies.length - 1]), 150);
                    }
                    this.draggedAssembly = null;
                });
        }

    }

    dragEnd(event) {
        this.draggedAssembly = null;
    }

    /**响应子组件中的拖拽变更事件 */
    onAssemblyClick(assembly: Assembly) {
        for (let i = 0; i < this.assemblies.length; i++) {
            let temp = this.assemblies[i];
            temp.shadow = 0;
            if (temp.id == assembly.id) {
                temp.shadow = 8;
                this.assemblies[i] = assembly;
            }
        }
        this.assembly = assembly;
    }
    /** 加载表单项 */
    loadFormAssemblies() {
        this.formDesignService.loadAssembliesByFormId(this.formIdValue)
            .subscribe(data => {
                let array = [];
                data.forEach(ele => {
                    let temp = new Assembly(ele);
                    temp.name = ele.assemblyName;
                    temp.labelName = ele.assemblyLabelName;
                    temp.value = ele.assemblyValue;
                    temp.authFlag = ele.authFlag;//是否需要授权
                    temp.authCode = ele.authCode;//读写权限
                    //样式
                    if (ele.styleAttributes) {
                        temp.attributes = new AssemblyStyles(JSON.parse(ele.styleAttributes));
                        temp.attributes.x = ele['positionX'];
                        temp.attributes.y = ele['positionY'];
                    }
                    //验证
                    temp.validators = new AssemblyValidators(ele.validAttributes ? JSON.parse(ele.validAttributes) : {});
                    //配置
                    temp.configs = new AssemblyConfigs(ele.configAttributes ? JSON.parse(ele.configAttributes) : {});
                    temp.attributes.refreshStyle();
                    array.push(temp);
                });
                this.assemblies = array;
            });
    }
}
